# -*- coding: utf-8 -*-
import os
import re
import stat
import codecs
import sys
import shutil
import string

from xml.sax import make_parser
from xml.sax.handler import ContentHandler

reload(sys)
sys.setdefaultencoding('utf-8')
encoding = "utf-8"

splashLayout = "app/src/main/res/layout/activity_welcom.xml"
manifestFile = "app/src/main/AndroidManifest.xml"
buildPath = "app/build.gradle"

releaseFileName = "Hulagyms_%s_%s.apk"  # 版本号
releaseFolder = "release"
tempFile = "app/build/outputs/apk/app-release.apk"
vercode_src = 'android:versionCode="\S*"'
vercode_dst = 'android:versionCode="%s"'
vername_src = 'android:versionName="\S*"'
vername_dst = 'android:versionName="%s"'

gegister_channel_src = 'android:name="TD_CHANNEL_ID" android:value="\S*"'
gegister_channel_dst = 'android:name="TD_CHANNEL_ID" android:value="%s"'
umeng_channel_src = 'android:name="UMENG_CHANNEL" android:value="\S*"'
umeng_channel__dst = 'android:name="UMENG_CHANNEL" android:value="%s"'

splashpic_src = 'android:src="@mipmap/\S*"'
splashpic_dst = 'android:src="@mipmap/%s"'


class AttributeSet:
    def __init__(self):
        self.channelCode = None
        self.channelName = None
        self.splashpic = None

    def toString(self):
        print "channelcode[%s]:channelname[%s]:splashpic[%s]" % (self.channelCode, self.channelName, self.splashpic)


class AttributeHandler(ContentHandler):
    def __init__(self):
        self.nodes = []
        self.root = None
        self.tag = None

    def startDocument(self):
        pass

    def endDocument(self):
        pass

    def startElement(self, name, attributes):
        self.tag = name
        if cmp(name, 'chnnelversion') == 0:
            self.root = AttributeSet()
            self.nodes.append(self.root)
        else:
            pass

    def characters(self, data):
        if self.tag is None:
            return
        if cmp(self.tag, 'channelcode') == 0:
            self.root.channelCode = data
        elif cmp(self.tag, 'chnnelname') == 0:
            self.root.channelName = data
        elif cmp(self.tag, 'splashpic') == 0:
            self.root.splashpic = data
        else:
            pass

    def endElement(self, name):
        self.tag = None


def main():
    (encoding)
    vercode = 0
    vername = None
    f = open(buildPath)
    lines = f.readlines()
    for line in lines:
        line = line.strip()
        if line.startswith("versionCode"):
            length = line.__len__()
            vercode = line[length - 3:length]
        if line.startswith("versionName"):
            length = line.__len__()
            vername = line[length - 6:length - 1]

    parser = make_parser()
    handler = AttributeHandler()
    parser.setContentHandler(handler)
    parser.parse("config.xml")
    for attr in handler.nodes:
        channelName = attr.channelName
        channelCode = attr.channelCode
        splashPic = attr.splashpic
        attr.toString()

        # 更换启动页
        splashLayoutFileStr = codecs.open(splashLayout, 'r', encoding).read()
        splashLayoutFileStr = re.sub(splashpic_src, splashpic_dst % splashPic, splashLayoutFileStr)
        codecs.open(splashLayout, 'w', encoding).write(splashLayoutFileStr)

        # 写版本号
        manifestFileStr = codecs.open(manifestFile, 'r', encoding).read()
        manifestFileStr = re.sub(vercode_src, vercode_dst % vercode, manifestFileStr)
        manifestFileStr = re.sub(vername_src, vername_dst % vername, manifestFileStr)
        # 写渠道号
        manifestFileStr = re.sub(gegister_channel_src, gegister_channel_dst % channelCode, manifestFileStr)
        manifestFileStr = re.sub(umeng_channel_src, umeng_channel__dst % channelName, manifestFileStr)
        codecs.open(manifestFile, 'w', encoding).write(manifestFileStr)

        # 编译
        os.popen("gradle clean").read()
        gradlePipe = os.popen("gradle assembleRelease").read()
        if not os.path.exists(tempFile):
            print "编译失败，请查看错误信息gradlelog.txt"
            print "gradle build failed, check the antlog.txt for more information."
            open("gradlelog.txt", "w").write(gradlePipe)
            continue
        if not os.path.exists(releaseFolder):
            os.makedirs(releaseFolder)
            # 拷贝到release目录
        shutil.copyfile(tempFile, os.path.join(releaseFolder, releaseFileName % (channelName, vername)))


if __name__ == "__main__":
    main()
